<template>
  <div class="contacts-container">
    <div class="main-content">
      <div class="search-bar">
        <div class="search-input">
          <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#666"/>
          </svg>
          <input 
            type="text" 
            placeholder="Find contact" 
            class="search-field" 
            v-model="searchQuery"
          />
        </div>
      </div>

      <div class="header">
        <h1 class="page-title">Contacts</h1>
        <div class="header-actions">
          <button class="action-btn" @click="openCreate()" title="Add contact">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" fill="#666"/>
            </svg>
          </button>
        </div>
      </div>

      <div class="contacts-content" v-if="filteredContacts.length > 0">
        <div class="contacts-list">
          <div 
            class="contact-item"
            v-for="c in filteredContacts"
            :key="c.id"
          >
            <div class="contact-avatar">
              <span class="avatar-text">{{ getInitials(c) }}</span>
            </div>
            <div class="contact-info">
              <div class="contact-name">{{ getDisplayName(c) }}</div>
              <div class="contact-sub">{{ c.job || c.company || c.sip || c.phone }}</div>
            </div>
            <div class="contact-actions">
              <button class="mini-btn" @click="dial(c)">Call</button>
            </div>
          </div>
        </div>
      </div>
      <div class="contacts-content" v-else>
        <div class="no-contacts">
          <p class="no-contacts-text">No contacts found</p>
        </div>
      </div>
    </div>

    <!-- 创建联系人抽屉 -->
    <div class="drawer" v-if="showCreate">
      <div class="drawer-header">
        <div class="drawer-title">New contact</div>
        <button class="drawer-close" @click="closeCreate">✕</button>
      </div>
      <div class="drawer-body">
        <div class="avatar-upload">
          <div class="avatar-circle">
            <span class="avatar-text">{{ getInitials(editing) || '👤' }}</span>
          </div>
          <label class="upload-btn">
            <input type="file" accept="image/*" @change="onAvatarChange" hidden />
            Add an image
          </label>
        </div>

        <div class="form-grid">
          <div class="form-group">
            <label>First name</label>
            <input class="input" v-model="editing.firstName" />
          </div>
          <div class="form-group">
            <label>Last name</label>
            <input class="input" v-model="editing.lastName" />
          </div>
          <div class="form-group">
            <label>Company</label>
            <input class="input" v-model="editing.company" />
          </div>
          <div class="form-group">
            <label>Job</label>
            <input class="input" v-model="editing.job" />
          </div>
          <div class="form-group">
            <label>SIP address</label>
            <input class="input" v-model="editing.sip" placeholder="1001@domain" />
          </div>
          <div class="form-group">
            <label>Phone</label>
            <input class="input" v-model="editing.phone" />
          </div>
        </div>
      </div>
      <div class="drawer-footer">
        <button class="secondary" @click="closeCreate">Cancel</button>
        <button class="primary" @click="saveContact">Save</button>
      </div>
    </div>
    <div class="drawer-mask" v-if="showCreate" @click="closeCreate"></div>
  </div>
</template>

<script>
export default {
  name: 'ContactsPage',
  data() {
    return {
      contacts: [],
      searchQuery: '',
      showCreate: false,
      editing: this.createEmptyContact(),
    }
  },
  computed: {
    filteredContacts() {
      if (!this.searchQuery) return this.contacts;
      const q = this.searchQuery.toLowerCase();
      return this.contacts.filter(c => {
        const name = `${c.firstName || ''} ${c.lastName || ''}`.toLowerCase();
        return (
          name.includes(q) ||
          (c.company || '').toLowerCase().includes(q) ||
          (c.job || '').toLowerCase().includes(q) ||
          (c.sip || '').toLowerCase().includes(q) ||
          (c.phone || '').toLowerCase().includes(q)
        );
      });
    }
  },
  mounted() {
    this.fetchContacts();
  },
  methods: {
    openCreate() {
      this.$router.push({ name: 'NewContact' });
    },
    createEmptyContact() {
      return { id: '', firstName: '', lastName: '', company: '', job: '', sip: '', phone: '', avatar: '' };
    },
    getDisplayName(c) {
      const name = `${c.firstName || ''} ${c.lastName || ''}`.trim();
      return name || c.sip || c.phone || 'Unnamed';
    },
    getInitials(c) {
      if (!c) return '';
      const a = (c.firstName || '').trim();
      const b = (c.lastName || '').trim();
      if (a || b) return `${a.charAt(0)}${b.charAt(0)}`.toUpperCase() || a.charAt(0).toUpperCase();
      if (c.company) return c.company.substring(0, 2).toUpperCase();
      if (c.sip) return c.sip.substring(0, 2).toUpperCase();
      if (c.phone) return c.phone.substring(0, 2).toUpperCase();
      return 'NA';
    },
    async fetchContacts() {
      try {
        const { invoke } = window.__TAURI__.core;
        this.contacts = await invoke('list_contacts');
      } catch (e) {
        console.error('加载联系人失败', e);
        this.contacts = [];
      }
    },
    closeCreate() {
      this.showCreate = false;
    },
    onAvatarChange(e) {
      const file = e.target.files && e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = () => { this.editing.avatar = reader.result; };
      reader.readAsDataURL(file);
    },
    async saveContact() {
      try {
        const id = crypto && crypto.randomUUID ? crypto.randomUUID() : String(Date.now());
        const payload = { ...this.editing, id };
        const { invoke } = window.__TAURI__.core;
        await invoke('add_contact', { contact: payload });
        this.showCreate = false;
        await this.fetchContacts();
      } catch (e) {
        console.error('保存联系人失败', e);
      }
    },
    dial(c) {
      const number = c.sip || c.phone;
      if (!number) return;
      this.$router.push({ name: 'NewCall', query: { number } });
    }
  }
}
</script>

<style scoped>
.contacts-container {
  height: 100vh;
  background: #fff;
}



/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 30px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 搜索栏 */
.search-bar {
  margin-bottom: 30px;
}

.search-input {
  position: relative;
  max-width: 100%;
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.search-field {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  font-size: 14px;
  background: #f8f9fa;
  outline: none;
  transition: border-color 0.3s ease;
}

.search-field:focus {
  border-color: #ff6b35;
  background: white;
}

.search-field::placeholder {
  color: #666;
}

/* 标题和操作按钮 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 12px;
  background: #f8f9fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.action-btn:hover {
  background: #e9ecef;
}

/* 联系人内容 */
.contacts-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-contacts {
  text-align: center;
}

.no-contacts-text {
  font-size: 18px;
  color: #1a1a1a;
  font-weight: 500;
  margin: 0;
}

/* 列表 */
.contacts-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 12px 14px;
  border-radius: 12px;
  background: #f8f9fa;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text { font-weight: 700; color: #5b6b7a; }

.contact-info { flex: 1; }
.contact-name { font-weight: 600; color: #1a1a1a; }
.contact-sub { font-size: 12px; color: #6c757d; }

.contact-actions { display: flex; gap: 8px; }
.mini-btn {
  border: none;
  background: #ff6b35;
  color: white;
  border-radius: 8px;
  padding: 6px 10px;
  cursor: pointer;
}

/* 抽屉 */
.drawer-mask {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.25);
}

.drawer {
  position: fixed;
  top: 0;
  right: 0;
  width: 520px;
  height: 100vh;
  background: #fff;
  box-shadow: -2px 0 20px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
}

.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}
.drawer-title { font-size: 22px; font-weight: 700; }
.drawer-close { border: none; background: transparent; font-size: 18px; cursor: pointer; }

.drawer-body { padding: 16px 24px; overflow: auto; }
.avatar-upload { display: flex; align-items: center; gap: 16px; margin-bottom: 20px; }
.avatar-circle { width: 90px; height: 90px; border-radius: 50%; background:#e9eef3; display:flex; align-items:center; justify-content:center; }
.upload-btn { color: #385a7c; cursor: pointer; }

.form-grid { display: grid; grid-template-columns: 1fr; gap: 14px; }
.form-group { display: flex; flex-direction: column; gap: 8px; }
.form-group label { color: #385a7c; font-weight: 600; }
.input { padding: 12px 14px; border: 1px solid #e0e0e0; border-radius: 20px; outline: none; background:#f8f9fa; }
.input:focus { border-color: #ff6b35; background: #fff; }

.drawer-footer { padding: 14px 24px; border-top: 1px solid #f0f0f0; display:flex; justify-content:flex-end; gap: 10px; }
.drawer-footer .secondary { background:#e9ecef; border:none; border-radius:10px; padding:10px 14px; cursor:pointer; }
.drawer-footer .primary { background:#ff6b35; color:#fff; border:none; border-radius:10px; padding:10px 16px; cursor:pointer; }
</style>
